package cn.edu.sdjzu.xg.bysj.service;


import cn.edu.sdjzu.xg.bysj.dao.UserDao;
import cn.edu.sdjzu.xg.bysj.domain.Actor;
import cn.edu.sdjzu.xg.bysj.domain.User;

import com.alibaba.fastjson.JSONObject;
import util.JdbcHelper;
import util.TokenHelper;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;

public final class UserService {
    private static final UserService userService = new UserService();
    private final UserDao userDao = UserDao.getInstance();

    public UserService() {
    }

    public static UserService getInstance() {
        return UserService.userService;
    }

    public Collection<User> getUsers() throws SQLException {
        return userDao.findAll();
	}
	
	public User getUser(Integer id)throws SQLException {
		return userDao.find(id);
	}
	
	public boolean updateUser(User user)throws SQLException {
		userDao.delete(user);
		return userDao.add(user);
	}
	
	public boolean addUser(User user)throws SQLException {
		return userDao.add(user);
	}

    public boolean deleteUser(Integer id) throws SQLException {
        User user = this.getUser(id);
        return this.deleteUser(user);
    }

    public boolean deleteUser(User user) throws SQLException {
        return userDao.delete(user);
    }

    public Actor login(User userToLogin, JSONObject message) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        Actor actor = userDao.login(connection, userToLogin);
        HashMap<Integer, String> map = new HashMap<Integer, String>();
        map.put(1,actor.getName());
        String token = TokenHelper.getToken(map);
        message.put("token", token);
        //System.out.println(token);
        JdbcHelper.close(connection);
        return actor;
    }
}
